package net.diaowen.dwsurvey.controller;

import net.diaowen.common.base.entity.User;
import net.diaowen.common.base.service.AccountManager;
import net.diaowen.common.plugs.page.Page;
import net.diaowen.common.utils.DiaowenProperty;
import net.diaowen.common.utils.ExportReportThread;
import net.diaowen.common.utils.UnansweredThread;
import net.diaowen.common.utils.excel.XLSExportUtil;
import net.diaowen.dwsurvey.entity.Question;
import net.diaowen.dwsurvey.entity.SurveyAnswer;
import net.diaowen.dwsurvey.entity.SurveyDirectory;
import net.diaowen.dwsurvey.entity.UserGroupInfo;
import net.diaowen.dwsurvey.service.SurveyAnswerManager;
import net.diaowen.dwsurvey.service.SurveyDirectoryManager;
import net.diaowen.dwsurvey.service.UserGroupInfoManager;
import net.diaowen.dwsurvey.service.impl.UserGroupInfoManagerImpI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 答卷数据
 * @author keyuan(keyuan258@gmail.com)
 *
 * https://github.com/wkeyuan/DWSurvey
 * http://dwsurvey.net
 *
 */
@Controller
@RequestMapping("/da/my-survey-answer")
public class MySurveyAnswerController{
	@Autowired
	private SurveyAnswerManager surveyAnswerManager;
	@Autowired
	private SurveyDirectoryManager directoryManager;
	@Autowired
	private AccountManager accountManager;
	@Autowired
	private UserGroupInfoManagerImpI userGroupInfo;

	protected final static String RESPONSE_ANSWER = "responseAnswer";

	@RequestMapping("/answer.do")
	public ModelAndView execute(HttpServletRequest request,Page<SurveyAnswer> page,String surveyId) throws Exception {
		ModelAndView modelAndView = new ModelAndView();
		User user=accountManager.getCurUser();
    	if(user!=null){
    		//如果是超级管理员则有权查看所有
    		SurveyDirectory survey = null;
    		if (user.getSystemRole() == 8) {
    			survey = directoryManager.get(surveyId);
    		} else {
    			survey = directoryManager.getSurveyByUser(surveyId, user.getId());
    		}
    		if(survey!=null){
    			page=surveyAnswerManager.answerPage(page, surveyId);
    		}
			modelAndView.addObject("page",page);
			modelAndView.addObject("survey",survey);
    	}
		modelAndView.addObject("surveyId",surveyId);
    	modelAndView.setViewName("/diaowen-da/survey-answer-data");
		return modelAndView;
	}

	@RequestMapping("/responseAnswer.do")
	public ModelAndView responseAnswer(String answerId) throws Exception {
		ModelAndView modelAndView = new ModelAndView();
		List<Question> questions = new ArrayList<Question>();
		try {
			SurveyDirectory directory=new SurveyDirectory();
			if (answerId != null) {
				SurveyAnswer answer = surveyAnswerManager.getModel(answerId);
				questions = surveyAnswerManager.findAnswerDetail(answer);
				User user=accountManager.getCurUser();
		    	if(answer.getSurveyId() != null && user!=null){
		    		//如果是超级管理员，则有权查看所有
		    		SurveyDirectory survey = null;
		    		if (user.getSystemRole() == 8) {
		    			survey = directoryManager.get(answer.getSurveyId());
		    		} else {
			    		survey = directoryManager.getSurveyByUser(answer.getSurveyId(), user.getId());		    			
		    		}
		    		if(survey!=null){
		    			modelAndView.addObject("questions", questions);
						modelAndView.addObject("directory", directory);
		    		}
		    	}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		modelAndView.setViewName("/diaowen-answer/response-answer");
		return modelAndView;
	}

	@RequestMapping("/delete.do")
	@ResponseBody
	public String delete(String answerId) throws Exception {
		String result="error";
		try{
			if (answerId != null) {
				SurveyAnswer answer = surveyAnswerManager.getModel(answerId);
				User user=accountManager.getCurUser();
		    	if(answer.getSurveyId() != null && user!=null){
		    		//如果是超级管理员，则有权查看所有
		    		SurveyDirectory survey = null;
		    		if (user.getSystemRole() == 8) {
		    			survey = directoryManager.get(answer.getSurveyId());
		    		} else {
			    		survey = directoryManager.getSurveyByUser(answer.getSurveyId(), user.getId());		    			
		    		}
		    		if(survey!=null){
		    			surveyAnswerManager.delete(answer);
						Integer answerNum = survey.getAnswerNum();
						if(answerNum!=null && answerNum>=1){
							survey.setAnswerNum(answerNum-1);
							directoryManager.save(survey);
						}
		    		}
		    	}
			}
			result="true";
		}catch(Exception e){
			e.printStackTrace();
		}
		return result;
	}

	@RequestMapping("/exportXLS.do")
	@ResponseBody
	public String exportXLS(HttpServletRequest request,HttpServletResponse response,String surveyId) throws Exception{
		try{
			String savePath = request.getSession().getServletContext().getRealPath("/");
			User user=accountManager.getCurUser();
	    	if(user!=null){
	    		//如果是超级管理员，则有权查看所有
	    		SurveyDirectory survey = null;
	    		if (user.getSystemRole() == 8) {
	    			survey = directoryManager.get(surveyId);
	    		} else {
		    		survey = directoryManager.getSurveyByUser(surveyId, user.getId());		    			
	    		}
	    		if(survey!=null){
					String basepath = surveyId + "";
					String urlPath = "/WEB-INF/expfile/" + basepath + "/";// 下载所用的地址
					String path = urlPath.replace("/", File.separator);// 文件系统路径
					String fileName = "DWSurvey-"+surveyId + ".xls";

					if(1==1){
						return "redirect:/response/answer-dwsurvey.do?surveyId="+surveyId+"&redType=10";
					}

					savePath = urlPath + fileName;
					System.out.println("savePath is+ "+savePath);
					response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode("dwsurvey_"+survey.getSid()+".xls", "UTF-8"));
					request.getServletContext().getRequestDispatcher(savePath).forward(request,response);

	    		}
	    	}
		}catch (Exception e) {
			e.printStackTrace();
		}

		 return null;
	}


	@RequestMapping("/exportXLSThread.do")
	public ModelAndView exportXLSThread(HttpServletRequest request,HttpServletResponse response,String surveyId) throws Exception{

		ModelAndView modelAndView = new ModelAndView();

		try{
			String savePath = request.getSession().getServletContext().getRealPath("/");
			User user=accountManager.getCurUser();
			if(user!=null){
				//如果是超级管理员，则有权查看所有
				SurveyDirectory survey = null;
				if (user.getSystemRole() == 8) {
					survey = directoryManager.get(surveyId);
				} else {
					survey = directoryManager.getSurveyByUser(surveyId, user.getId());
				}
				if(survey!=null){

					ExportReportThread exReportThread = new ExportReportThread();
					exReportThread.setSavePath(savePath);
					exReportThread.setSurveyId(surveyId);
					exReportThread.setSurveyAnswerManager(surveyAnswerManager);
					exReportThread.start();
					/**
					 savePath=surveyAnswerManager.exportXLS(surveyId,savePath);
					 //					savePath = URLEncoder.encode(savePath, "utf-8");
					 //	    			response.sendRedirect(request.getContextPath()+savePath);
					 System.out.println("savePath:"+savePath);
					 response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode("dwsurvey_"+survey.getSid()+".xls", "UTF-8"));
					 request.getServletContext().getRequestDispatcher(savePath).forward(request,response);
					 **/
				}
			}
		}catch (Exception e) {
			e.printStackTrace();
		}

		modelAndView.setViewName("/diaowen-answer/geReport");

		return modelAndView;
	}

	/**
	 * 下载方法
	 * @param request
	 * @param response
	 * @param surveyId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/DownLoadXLSThread.do")
	public ModelAndView DownLoadXLSThread(HttpServletRequest request,HttpServletResponse response,String surveyId) throws Exception{

		ModelAndView modelAndView = new ModelAndView();

		try{
			String savePath = request.getSession().getServletContext().getRealPath("/");
			String path="";
			String downloadPath="";
			String realname="Data.xls";

			User user=accountManager.getCurUser();


			if(user!=null){
				//如果是超级管理员，则有权查看所有
				SurveyDirectory survey = null;
				if (user.getSystemRole() == 8) {
					survey = directoryManager.get(surveyId);
				} else {
					survey = directoryManager.getSurveyByUser(surveyId, user.getId());
				}
				if(survey!=null){

					try{
						String frontPath= DiaowenProperty.DOWN_LOAD_PATH;
						downloadPath=frontPath+"/WEB-INF/expfile/"+surveyId+"/DWSurvey-"+surveyId+".xls";
						OutputStream output = response.getOutputStream();
						FileInputStream fis = new FileInputStream(downloadPath);
						response.reset();//可以加也可以不加
						response.setContentType("application/x-download");//设置为下载application/x-download
						response.addHeader("Content-Disposition", "attachment;filename="+ realname);//下载文件时，显示的文件名
						byte[] b = new byte[1024];
						int i = 0;
						while ((i = fis.read(b)) > 0) {
							output.write(b, 0, i);
						}
						output.flush();
						fis.close();
						output.close();
						File file=new File(downloadPath);
						if (file.exists()){
							file.delete();
						}
						request.getSession().removeAttribute(surveyId);
						return null;
					}catch (Exception e){
						String exl= (String) request.getSession().getAttribute(surveyId);
						if (exl!=null){
							if (exl.equals(surveyId)){
								modelAndView.addObject("prompt","正在生成中,请您稍等一会");
								modelAndView.setViewName("/diaowen-answer/transcode");
								return modelAndView;
							}
						}else {
							request.getSession().setAttribute(surveyId,surveyId);
							ExportReportThread exReportThread = new ExportReportThread();
							exReportThread.setSavePath(savePath);
							exReportThread.setSurveyId(surveyId);
							exReportThread.setSurveyAnswerManager(surveyAnswerManager);
							exReportThread.start();
						}

						modelAndView.setViewName("/diaowen-answer/transcode");
						return modelAndView;
					}

				}
			}
		}catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	@RequestMapping("/DownLoadUnansweredList.do")
	public ModelAndView listOfUnansweredStudents(HttpServletRequest request,HttpServletResponse response,String surveyId){

		ModelAndView modelAndView = new ModelAndView();
		try{
			String savePath = request.getSession().getServletContext().getRealPath("/");
			String path="";
			String downloadPath="";
			String realname="UnansweredData.xls";

			User user=accountManager.getCurUser();


			if(user!=null){
				//如果是超级管理员，则有权查看所有
				SurveyDirectory survey = null;
				if (user.getSystemRole() == 8) {
					survey = directoryManager.get(surveyId);
				} else {
					survey = directoryManager.getSurveyByUser(surveyId, user.getId());
				}
				if(survey!=null){
						userGroupInfo.exportXLS(surveyId,savePath);
						unansweredExport(request, response, surveyId, realname, "/unansweredSurvey-", surveyId + "u");
						return null;
				}
			}
		}catch (Exception e){
			e.printStackTrace();
		}

		return null;
	}

	public void generateTable(HttpServletRequest request, String surveyId, String savePath) {
		request.getSession().setAttribute(surveyId +"u", surveyId);
		UnansweredThread exReportThread = new UnansweredThread();
		exReportThread.setSavePath(savePath);
		exReportThread.setSurveyId(surveyId);
		exReportThread.setUserGroupInfo(userGroupInfo);
		exReportThread.start();
	}

	public void unansweredExport(HttpServletRequest request, HttpServletResponse response, String surveyId, String realname, String s, String s2) throws IOException {
		String downloadPath;
		String frontPath = DiaowenProperty.DOWN_LOAD_PATH;
		downloadPath = frontPath + "/WEB-INF/expfile/" + surveyId + s + surveyId + ".xls";
		OutputStream output = response.getOutputStream();
		FileInputStream fis = new FileInputStream(downloadPath);
		response.reset();//可以加也可以不加
		response.setContentType("application/x-download");//设置为下载application/x-download
		response.addHeader("Content-Disposition", "attachment;filename=" + realname);//下载文件时，显示的文件名
		byte[] b = new byte[1024];
		int i = 0;
		while ((i = fis.read(b)) > 0) {
			output.write(b, 0, i);
		}
		output.flush();
		fis.close();
		output.close();
		File file = new File(downloadPath);
		if (file.exists()) {
			file.delete();
		}
		request.getSession().removeAttribute(s2);
	}
}
